<template>
  <a-drawer
    v-model:visible="show"
    :width="520"
    title="编辑设备"
    :confirm-loading="confirmLoading"
    :get-container="getContainer"
    @ok="ok"
  >
    <div ref="content" class="mx-auto">
      <DynamicForm
        v-if="show"
        ref="dyFormIns"
        :model="model"
        :model-form-setting="modelFormSetting"
        :force-column="true"
      />
      <a-form ref="equipmentAttrForm" name="attr_form" :model="customeAttrForm" layout="vertical">
        <div
          v-for="(customerAttr, index) in customeAttrForm.customeAttr"
          :key="index"
          class="flex flex-row items-center"
        >
          <a-form-item
            class="mr-7 flex-1"
            :name="['customeAttr', index, 'customLabel']"
            label="属性名称"
            :rules="{
              message: '请输入自定义属性名称',
            }"
          >
            <a-input v-model:value="customerAttr.customLabel" :maxlength="32" />
          </a-form-item>
          <a-form-item
            class="mr-7 flex-1"
            label="属性内容"
            :name="['customeAttr', index, 'customValue']"
            :rules="{
              message: '请输入自定义属性内容',
            }"
          >
            <a-input v-model:value="customerAttr.customValue" :maxlength="32" />
          </a-form-item>
          <div>
            <delete-outlined class="text-2xl !text-color-danger" @click="removeAttr(customerAttr)" />
          </div>
        </div>
        <a-form-item class="mb-0">
          <a-button type="link" class="!p-0" @click="addAttr">
            <template #icon>
              <Icon type="icon-tianjia" />
            </template>
            添加自定义属性
          </a-button>
        </a-form-item>
      </a-form>
    </div>
    <template #footer>
      <div class="flex flex-row items-center justify-end mt-4">
        <a-button @click="show = false">取消</a-button>
        <a-button type="primary" class="ml-4" @click="ok">确认</a-button>
      </div>
    </template>
    <a-modal
      v-model:visible="selectEquipmentTypeVisible"
      title="选择设备机型"
      width="900px"
      height="600px"
      class="dispatchContainer"
      @ok="handleSelectEquipmentType"
    >
      <div ref="content" class="mx-auto">
        <EquipmentTypeSelect
          ref="equipmentTypeIns"
          v-model:value="selectedEquipmentTypeId"
          :single-select="true"
          :is-enterprise="true"
        />
      </div>
    </a-modal>
    <SelectOrganizationUserModal v-model:visible="chooseUserVisible" @ok="handleChooseUserOkFn" />
  </a-drawer>
</template>
<script lang="ts" setup>
import { ref, watch, nextTick, h, onMounted, computed } from "vue";
import { DynamicFormExpose, FormItemComponentType, FormItemData } from "../../CURDDialog/models";
import { EquipmentItem, EquipmentTypeItem, ParEquipmentDetail } from "/@/api/aiot/equipment/models";
import { updateEquipment } from "/@/api/aiot/equipment";
import { projectsPage } from "/@/api/aiot/projectManage";
import { PatternKey } from "/@/utils/verify";
import SelectInput from "/@/components/common/SelectInput.vue";
import { brandsPage } from "/@/api/aiot/brand";
import { gatewayPage } from "/@/api/aiot/gateway";
import { getEquipmentDetail } from "/@/api/aiot/equipment";
import dayjs from "dayjs";
import SelectOrganizationUserModal from "/@/views/aiot/enterprise/ProjectManage/SelectOrganizationUserModal.vue";
import { DeleteOutlined } from "@ant-design/icons-vue";
import { CustomAttributesItem } from "/@/api/aiot/projectManage/models";
import { message } from "ant-design-vue";
import { pageEquipmentCategoryEnter } from "/@/api/aiot/deviceType";

const props = defineProps<{
  id?: string;
  projectId?: string;
  getContainer?: () => HTMLElement;
}>();
const equipmentAttrForm = ref();
const equipmentTypeIns = ref();
const emits = defineEmits(["update:id", "ok", "successFn"]);
const confirmLoading = ref<boolean>(false);
const show = ref<boolean>(false);
const selectEquipmentTypeVisible = ref<boolean>(false);
const selectedEquipmentTypeId = ref<string[]>([]);
const slaveIdTemp = ref<number>(0);
const chooseUserVisible = ref(false);
const dyFormIns = ref<DynamicFormExpose>();
const model = ref<ParEquipmentDetail>({
  equipmentName: "",
  equipmentNo: "",
  projectId: "",
  equipmentCategoryId: "",
  equipmentType: "",
  brandId: "",
  location: "",
  equipmentTags: "",
  equipmentTypeId: "",
  gatewayId: "",
  connectType: "0",
  slavType: "0",
  slaveId: 0,
  equipmentPhotos: [],
  nameplateInfo: [],
  serialNumber: "",
  manufacturer: "",
  specification: "",
  chargePerson: "",
  useDate: "",
  descriptions: "",
  equipmentId: "",
  chargePersonId: "",
  additionalinfo: "",
});
const modelFormSetting: FormItemData[] = [
  {
    key: "_subTitle",
    beforeKey: "equipmentName",
    subTitle: "基本信息",
  },
  {
    key: "equipmentName",
    label: "设备名称",
    max: 32,
    required: true,
  },
  {
    key: "equipmentNo",
    label: "设备编号",
    labelDes: "支持大小写字母、数字和下划线",
    pattern: PatternKey.code,
    max: 32,
    required: true,
  },
  {
    key: "projectId",
    label: "所属项目",
    required: true,
    type: FormItemComponentType.SELECT,
    async getData() {
      const data = await projectsPage();
      return data
        ? data?.records.map((el) => ({
            label: el.projectName,
            value: el.projectId,
          }))
        : [];
    },
    props: {
      disabled: true,
      options: [],
      getPopupContainer(node) {
        return node.parentNode;
      },
    },
  },
  {
    key: "equipmentCategoryId",
    label: "设备类别",
    type: FormItemComponentType.TREESELECT,
    getData: async () => {
      let equipmentCategoryData = (await pageEquipmentCategoryEnter())?.records || [];
      return equipmentCategoryData;
    },
    props: {
      fieldNames: { label: "equipmentCategoryName", value: "equipmentCategoryId" },
    },
  },
  {
    label: "设备机型",
    key: "equipmentType",
    props: {
      placeholder: "请选择",
      disabled: true,
    },
    // customComponent: h(SelectInput, {
    //   onClick() {
    //     selectEquipmentTypeVisible.value = true;
    //   },
    // }),
  },
  {
    key: "brandId",
    label: "设备品牌",
    required: true,
    type: FormItemComponentType.SELECT,
    async getData() {
      const data = await brandsPage();
      return data
        ? data.records.map((el) => ({
            label: el.brandChineseName,
            value: el.brandId,
          }))
        : [];
    },
    props: {
      options: [],
      getPopupContainer(node) {
        return node.parentNode;
      },
    },
  },
  {
    key: "location",
    label: "安装位置",
    max: 32,
    labelDes: "建议按照“园区-建筑-楼层录入”",
  },
  {
    key: "equipmentTags",
    label: "设备标签",
    type: FormItemComponentType.SELECT,
    props: {
      options: [
        { label: "重点设备", value: "important" },
        { label: "普通设备", value: "normal" },
      ],
    },
  },
  {
    key: "equipmentTypeId",
    hide: true,
  },
  {
    key: "equipmentId",
    hide: true,
  },
  {
    key: "_subTitle",
    beforeKey: "gatewayId",
    subTitle: "接入信息",
  },

  {
    key: "gatewayId",
    label: "所属网关",
    required: true,
    type: FormItemComponentType.SELECT,
    async getData({ params }) {
      if (!params) return [];
      const data = await gatewayPage({ size: 999, current: 1, model: { projectId: params || "" } });
      return data
        ? data.records.map((el) => ({
            label: el.gatewayName,
            value: el.gatewayId,
          }))
        : [];
    },
    props: {
      disabled: true,
      options: [],
      getPopupContainer(node) {
        return node.parentNode;
      },
    },
  },
  {
    key: "connectType",
    label: "接入方式",
    required: true,
    type: FormItemComponentType.SELECT,
    props: {
      options: [
        { label: "默认", value: "0" },
        { label: "modbus", value: "1" },
      ],
    },
  },
  {
    key: "slavType",
    label: "主从模式",
    required: true,
    type: FormItemComponentType.SELECT,
    hide: true,
    props: {
      options: [
        { label: "主机", value: "0" },
        { label: "从机", value: "1" },
      ],
    },
  },
  {
    key: "slaveId",
    label: "从机地址",
    required: true,
    labelDes: "取值范围1-255",
    pattern: PatternKey.maxNumber255,
    hide: true,
  },
  {
    key: "_subTitle",
    beforeKey: "equipmentPhotos",
    subTitle: "其他信息",
  },
  {
    key: "equipmentPhotos",
    label: "设备图片",
    labelDes: "建议尺寸1600像素*900像素，仅支持jpg/jpeg/png/gif格式，若不设置则系统默认",
    type: FormItemComponentType.IMGUPLOAD,
    props: {
      max: 6,
    },
  },
  {
    key: "nameplateInfo",
    label: "铭牌图片",
    labelDes: "支持jpg/jpeg/png/gif格式",
    type: FormItemComponentType.IMGUPLOAD,
    props: {
      max: 6,
    },
  },
  {
    key: "serialNumber",
    label: "设备序列号",
    max: 32,
  },
  {
    key: "manufacturer",
    label: "生产厂商",
    max: 32,
  },
  {
    key: "specification",
    label: "规格型号",
    max: 32,
  },
  {
    key: "chargePerson",
    label: "设备责任人",
    customComponent: h(SelectInput, {
      onClick() {
        chooseUserVisible.value = true;
      },
    }),
  },
  {
    key: "useDate",
    label: "投入使用时间",
    type: FormItemComponentType.DATEPICKER,
    props: {
      class: "w-full",
      format: "YYYY-MM-DD",
      valueFormat: "YYYY-MM-DD",
    },
  },
  {
    key: "descriptions",
    label: "设备简介",
    max: 200,
  },
  { key: "chargePersonId", hide: true },
  { key: "additionalinfo", hide: true },
];
onMounted(() => {});
watch(
  () => model.value.projectId,
  (v) => {
    model.value.gatewayId = "";
    nextTick(() => {
      dyFormIns.value?.reloadFormItemComponentData("gatewayId", v);
    });
  }
);
// 默认模式 slaveId = null modbus 主机 0 从机1-255
watch(
  () => model.value.slavType,
  (v) => {
    dyFormIns.value?.toggleField("slaveId", v === "0");
    nextTick(() => {
      if (v === "0") {
        slaveIdTemp.value = 0;
        model.value.slaveId = 0;
      } else if (v === "1") {
        model.value.slaveId = slaveIdTemp.value || 1;
      }
    });
  }
);
watch(
  () => model.value.connectType,
  (v) => {
    nextTick(() => {
      dyFormIns.value?.toggleField("slavType", v !== "1");
      dyFormIns.value?.toggleField("slaveId", v !== "1" || model.value.slavType !== "1");
    });
  },
  {
    immediate: true,
  }
);
const reqEquipmentInfo = ref<ParEquipmentDetail>();
watch(
  () => props.id,
  async (v) => {
    if (v) {
      show.value = true;
      let req = await getEquipmentDetail(v);
      reqEquipmentInfo.value = req || {};
      reqEquipmentInfo.value.slaveId !== null ? (slaveIdTemp.value = req?.slaveId || 0) : "";
      for (let key in model.value) {
        if (key !== "useDate") {
          if (req) {
            model.value[key] = req[key] || "";
          }
          if (req && req.equipmentInfo && req.equipmentInfo[key]) {
            model.value[key] = req.equipmentInfo[key];
          }
        }
      }
      model.value.slaveId = req?.slaveId;
      model.value.brandId = (req && req?.brandVo?.brandId) || "";
      model.value.equipmentPhotos = (req && req.equipmentInfo && req?.equipmentInfo.equipmentPhotoList) || [];
      model.value.nameplateInfo = (req && req?.equipmentInfo?.nameplateInfoList) || [];
      // model.value.equipmentInfo.additionalinfo
      if (req?.equipmentInfo && req.equipmentInfo.additionalinfo) {
        customeAttrForm.value.customeAttr = req.equipmentInfo.additionalinfo as any;
      }
      if (req && req.useDate) {
        model.value.useDate = dayjs(req.useDate).format("YYYY-MM-DD");
      }
      // 判断主从模式 链接方式
      /**
       * slavType
       * { label: "主机", value: "0" },
        { label: "从机", value: "1" },
        connectType
        1 默认 modbus

       */
      // 如果链接方式不等于modbus 那就等于默认
      model.value.connectType = req?.connectType;
      if (model.value.connectType !== "1") {
        model.value.connectType = "0";
        // model.value.slaveId = 0;
      }
      // 主从机判断
      if (model.value.slaveId === 0) {
        model.value.slavType = "0";
      } else {
        model.value.slavType = "1";
      }
      nextTick(() => {
        dyFormIns.value?.initFormItemComponentData();
        model.value.gatewayId = req?.gatewayId;
        // dyFormIns.value?.reloadFormItemComponentData("gatewayId", req?.projectId);
        equipmentTypeIns.value?.reset();
      });
    }
  }
);
watch(show, (v) => {
  if (!v) {
    reset();
  }
});
function reset() {
  dyFormIns.value?.resetFields;
  dyFormIns.value?.initFormItemComponentData();
  equipmentAttrForm.value?.resetFields();
  emits("update:id", "");
  model.value.chargePerson = "";
  model.value.chargePersonId = "";
  model.value.projectId = "";
  model.value.connectType = undefined;
  reqEquipmentInfo.value = {};
  customeAttrForm.value = {
    customeAttr: [],
  };
}
function ok() {
  dyFormIns.value?.validate().then(async () => {
    let obj = Object.assign({}, model.value);
    if (model.value.connectType === "0") {
      obj.slaveId = null;
    }
    obj.additionalinfo = JSON.stringify(customeAttrForm.value.customeAttr);
    let req = await updateEquipment(obj);
    if (req) {
      message.success("操作成功");
      show.value = false;
      emits("successFn");
    }
  });
}
const selectedEquipmentType = ref<EquipmentTypeItem[]>([]);
function handleSelectEquipmentType() {
  selectedEquipmentType.value = equipmentTypeIns.value.getSelecedEquipmentType();
  model.value.equipmentType = selectedEquipmentType.value[0].equipmentTypeName;
  model.value.equipmentTypeId = selectedEquipmentType.value[0].equipmentTypeId;
  selectEquipmentTypeVisible.value = false;
}
function handleChooseUserOkFn(selectUser) {
  if (selectUser.length <= 0) {
    message.warning("请选择用户");
    return;
  } else {
    model.value.chargePerson = selectUser[0].userName;
    model.value.chargePersonId = selectUser[0].userId;
  }
}
// 自定义属性
const customeAttrForm = ref<{ customeAttr: CustomAttributesItem[] }>({
  customeAttr: [],
});
function removeAttr(item: CustomAttributesItem) {
  let index = customeAttrForm.value.customeAttr.indexOf(item);
  if (index !== -1) {
    customeAttrForm.value.customeAttr.splice(index, 1);
  }
}
function addAttr() {
  if (customeAttrForm.value.customeAttr && customeAttrForm.value.customeAttr.length === 10) {
    message.warning("最多只能添加10条自定义属性");
    return;
  }
  customeAttrForm.value.customeAttr.push({
    customLabel: undefined,
    customValue: undefined,
  });
}
</script>
